package com.cy.comstore.controller;


import com.cy.comstore.service.ICartService;
import com.cy.comstore.util.JsonResult;
import com.cy.comstore.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xsn
 * @since 2023-03-03
 */
@RestController
@RequestMapping("/carts")
public class CartController extends BaseController{
    @Autowired
    private ICartService cartService;

    //一般我们需要id而不是amount这样的数据的时候就会使用rest风格来映射
    //但是产品界面已经通过js获取了商品pid 所以不需要rest风格的url  而且amount可以通过表单数量那里的id来获取值
    @RequestMapping("/insert")
    public JsonResult<Void> insert(Integer pid, Integer amount, HttpSession session){
        cartService.insertCart(getUidFromSession(session),pid,amount,getUsernameFromSession(session));
        return new JsonResult<Void>(OK);
    }

    @GetMapping({"/",""})
    public JsonResult<List<CartVO>> getVOByUid(HttpSession session){
        List<CartVO> list = cartService.getVOByUid(getUidFromSession(session));
        return new JsonResult<>(OK,list);
    }

    @RequestMapping("{cid}/num/add")
    public JsonResult<Integer> addNum(@PathVariable("cid") Integer cid, HttpSession session) {
        Integer integer = cartService.addNum(cid,getUidFromSession(session),getUsernameFromSession(session));
        return new JsonResult<>(OK,integer);
    }

    @RequestMapping("{cid}/num/sub")
    public JsonResult<Integer> subNum(@PathVariable("cid") Integer cid, HttpSession session) {
        Integer integer = cartService.subNum(cid,getUidFromSession(session),getUsernameFromSession(session));
        return new JsonResult<>(OK,integer);
    }

    @RequestMapping("/list")
    public JsonResult<List<CartVO>> getVOByCids(Integer[] cids, HttpSession session) {
        List<CartVO> list = cartService.getVOByCids(getUidFromSession(session), cids);
        return new JsonResult<>(OK,list);
    }

    @RequestMapping("/delete")
    public JsonResult<Boolean> deleteByCids(Integer[] cids){
        Boolean aBoolean = cartService.deleteByCids(cids);
        return new JsonResult<>(OK,aBoolean);
    }
}

